<template>
  <div>
    <n-space mb-4>
      <n-button type="primary" @click="handleAddTeam">新建团队</n-button>
    </n-space>

    <n-data-table :columns="columns" :data="data" />

    <edit
      v-model:showModal="showModal"
      :current-team="currentTeam"
      :type="opType"
      @submit-callback="getData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { NButton, NSpace, NDataTable } from "naive-ui";
import Edit from "./components/Edit.vue";
import type { TeamModel } from "@/api/team/model";
import dayjs from "dayjs";
import { getTeamList, deleteTeam } from "@/api/team";
import { dialog, message } from "@/utils/message";

const showModal = ref(false);
const currentTeam = ref<TeamModel>({
  id: 0,
  name: "",
  introduce: "",
  creator_by: "",
  created_at: "",
  members: [],
});
const columns = ref([
  {
    title: "团队名称",
    key: "name",
  },
  {
    title: "团队描述",
    key: "introduce",
  },
  {
    title: "创建时间",
    key: "created_at",
    render(row: TeamModel) {
      return dayjs(row.created_at).format("YYYY-MM-DD HH:mm:ss");
    },
  },
  {
    title: "创建人",
    key: "creator_by",
  },
  {
    title: "操作",
    key: "action",
  },
]);
const opType = ref<"add" | "edit">("add");
const data = ref<TeamModel[]>([]);

const handleAddTeam = () => {
  showModal.value = true;
  opType.value = "add";
};

const handleEditTeam = (row: TeamModel) => {
  currentTeam.value = row;
  showModal.value = true;
  opType.value = "edit";
};

const handleDeleteTeam = (row: TeamModel) => {
  dialog.error({
    title: "确定删除该团队吗？",
    content: "删除后将无法恢复",
    positiveText: "删除",
    negativeText: "取消",
    onPositiveClick: async () => {
      try {
        await deleteTeam(row.id!);
        message.success("删除成功");
        getData();
      } catch (_) {
        message.error("删除失败");
      }
    },
  });
};

const getData = async () => {
  const res = await getTeamList();
  if (res.code === 200) {
    data.value = res.data;
  } else {
    message.error(res.message);
  }
};
getData();
</script>
